package com.campus.controller;

import com.campus.common.Result;
import com.campus.common.TokenManager;
import com.campus.domain.Dto.UserLoginDto;
import com.campus.domain.Dto.UserRegisterDto;
import com.campus.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;

import static com.campus.common.BusinessConstants.TOKEN_KEY;
import static com.campus.common.BusinessConstants.USER_KEY;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody @Validated UserRegisterDto userRegisterDto){

        int rs = userService.register(userRegisterDto);

        if (rs > 0){
            return Result.success("添加成功");
        }else {
            return Result.error("添加失败，请联系管理员");
        }
    }

    @PostMapping("/login")
    public Result<String> login(HttpServletRequest request,
                                        @NotBlank @RequestParam String loginName,
                                        @NotBlank @RequestParam  String password)  {

        log.info(" username: {}, password: {}",loginName,password);
        UserLoginDto user = userService.login(loginName, password);
        if (ObjectUtils.isEmpty(user)) {
            return Result.error(200,"用户名或密码错误");
        }
        // session 中存储user
        HttpSession session = request.getSession() ;
        session.setAttribute(USER_KEY, user.getLoginName()) ;
        String token = TokenManager.getToken(user) ;
        session.setAttribute(TOKEN_KEY,token);
        return Result.success(500,"登录成功",token);
    }

    @GetMapping("/select")
    public Result select(String loginName, Long id){
        return Result.success(userService.select(loginName,id));
    }
}
